<template>
  <div class="work-order-container">
    <el-card shadow="hover">
      <el-form :inline="true">
        <el-form-item label="工单状态">
          <el-select v-model="state.filters.status" placeholder="全部" clearable style="width:160px">
            <el-option label="待处理" value="pending" />
            <el-option label="处理中" value="processing" />
            <el-option label="已解决" value="resolved" />
            <el-option label="已关闭" value="closed" />
          </el-select>
        </el-form-item>
        <el-form-item label="优先级">
          <el-select v-model="state.filters.priority" placeholder="全部" clearable style="width:160px">
            <el-option label="低" value="low" />
            <el-option label="中" value="medium" />
            <el-option label="高" value="high" />
            <el-option label="紧急" value="urgent" />
          </el-select>
        </el-form-item>
        <el-form-item label="问题分类">
          <el-select v-model="state.filters.category" placeholder="全部" clearable style="width:160px">
            <el-option label="库存问题" value="inventory" />
            <el-option label="订单问题" value="order" />
            <el-option label="仓库操作" value="warehouse" />
            <el-option label="系统问题" value="system" />
            <el-option label="其他" value="other" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-input v-model="state.filters.keyword" placeholder="工单号/标题/用户名..." style="width:260px" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleQuery">查询</el-button>
          <el-button type="success" @click="batchProcess(state.selectData)" :disabled="!state.selectData.length">
            批量处理
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 统计信息 -->
    <el-card shadow="hover" style="margin-top: 5px">
      <template #header>
        <span>工单统计</span>
      </template>
      <div style="display: flex; gap: 30px; align-items: center;">
        <div style="text-align: center;">
          <div style="font-size: 24px; font-weight: bold; color: #409eff;">{{ state.statistics.total }}</div>
          <div style="color: #666; font-size: 12px;">总工单</div>
        </div>
        <div style="text-align: center;">
          <div style="font-size: 24px; font-weight: bold; color: #e6a23c;">{{ state.statistics.pending }}</div>
          <div style="color: #666; font-size: 12px;">待处理</div>
        </div>
        <div style="text-align: center;">
          <div style="font-size: 24px; font-weight: bold; color: #67c23a;">{{ state.statistics.resolved }}</div>
          <div style="color: #666; font-size: 12px;">已解决</div>
        </div>
        <div style="text-align: center;">
          <div style="font-size: 24px; font-weight: bold; color: #f56c6c;">{{ state.statistics.urgent }}</div>
          <div style="color: #666; font-size: 12px;">紧急</div>
        </div>
      </div>
    </el-card>

    <!-- 工单列表 -->
    <el-card class="full-table" shadow="hover" style="margin-top: 5px">
      <el-table :data="state.tableData" v-loading="state.loading" @selection-change="(val:any[])=>state.selectData=val" row-key="id" border>
        <el-table-column type="selection" width="40" />
        <el-table-column prop="orderCode" label="工单号" width="160" />
        <el-table-column label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="getStatusType(row.status)" size="small">
              {{ getStatusText(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="优先级" width="100">
          <template #default="{ row }">
            <el-tag :type="getPriorityType(row.priority)" size="small">
              {{ getPriorityText(row.priority) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="title" label="标题" min-width="200" show-overflow-tooltip />
        <el-table-column prop="userName" label="创建人" width="120" />
        <el-table-column prop="category" label="分类" width="120">
          <template #default="{ row }">
            {{ getCategoryText(row.category) }}
          </template>
        </el-table-column>
        <el-table-column prop="assignedToName" label="处理人" width="120" />
        <el-table-column prop="createTime" label="创建时间" width="180" />
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button size="small" @click="viewWorkOrder(row)">查看</el-button>
            <el-button 
              v-if="row.status === 'pending'" 
              type="primary" 
              size="small" 
              @click="processWorkOrder(row)"
            >
              处理
            </el-button>
            <el-button 
              v-if="row.status === 'processing'" 
              type="success" 
              size="small" 
              @click="resolveWorkOrder(row)"
            >
              解决
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 工单详情对话框 -->
    <el-dialog
      v-model="workOrderDetailVisible"
      :title="`工单详情 - ${currentWorkOrder?.orderCode}`"
      width="800px"
      :close-on-click-modal="false"
    >
      <div v-if="currentWorkOrder" class="work-order-detail">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="工单号">{{ currentWorkOrder.orderCode }}</el-descriptions-item>
          <el-descriptions-item label="状态">
            <el-tag :type="getStatusType(currentWorkOrder.status)">
              {{ getStatusText(currentWorkOrder.status) }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="优先级">
            <el-tag :type="getPriorityType(currentWorkOrder.priority)">
              {{ getPriorityText(currentWorkOrder.priority) }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="分类">{{ getCategoryText(currentWorkOrder.category) }}</el-descriptions-item>
          <el-descriptions-item label="创建人">{{ currentWorkOrder.userName }}</el-descriptions-item>
          <el-descriptions-item label="处理人">{{ currentWorkOrder.assignedToName || '未分配' }}</el-descriptions-item>
          <el-descriptions-item label="创建时间">{{ currentWorkOrder.createTime }}</el-descriptions-item>
          <el-descriptions-item label="更新时间">{{ currentWorkOrder.updateTime || '无' }}</el-descriptions-item>
          <el-descriptions-item label="关联订单" :span="2">
            {{ currentWorkOrder.relatedOrderCode || '无' }}
          </el-descriptions-item>
        </el-descriptions>
        
        <el-divider>问题描述</el-divider>
        <div class="description-content">
          {{ currentWorkOrder.description }}
        </div>

        <el-divider>对话历史</el-divider>
        <div class="conversation-history">
          <div 
            v-for="msg in conversationHistory" 
            :key="msg.id"
            :class="['conversation-item', msg.isFromUser ? 'user' : 'agent']"
          >
            <div class="conversation-header">
              <span class="sender">{{ msg.userName }}</span>
              <span class="time">{{ formatTime(msg.timestamp) }}</span>
            </div>
            <div class="conversation-content">{{ msg.message }}</div>
          </div>
        </div>
      </div>
      
      <template #footer>
        <el-button @click="workOrderDetailVisible = false">关闭</el-button>
        <el-button 
          v-if="currentWorkOrder?.status === 'pending'" 
          type="primary" 
          @click="processWorkOrder(currentWorkOrder)"
        >
          处理工单
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup name="WorkOrder">
import { ref, reactive, onMounted } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { useCustomerServiceApi, type WorkOrder, type CustomerServiceMessage } from '/@/api/customerService';

const customerServiceApi = useCustomerServiceApi();

const state = reactive({
  loading: false,
  tableData: [] as WorkOrder[],
  selectData: [] as WorkOrder[],
  params: { page: 1, pageSize: 20 },
  filters: { 
    keyword: '', 
    status: '', 
    priority: '', 
    category: '' 
  },
  statistics: {
    total: 0,
    pending: 0,
    resolved: 0,
    urgent: 0
  }
});

const workOrderDetailVisible = ref(false);
const currentWorkOrder = ref<WorkOrder | null>(null);
const conversationHistory = ref<CustomerServiceMessage[]>([]);

// 查询工单列表
const handleQuery = async () => {
  state.loading = true;
  try {
    const params = { ...state.params, ...state.filters };
    const res = await customerServiceApi.getWorkOrderStatus(params);
    state.tableData = res.data?.result?.items || [];
    calculateStatistics();
  } finally {
    state.loading = false;
  }
};

// 计算统计信息
const calculateStatistics = () => {
  const stats = {
    total: state.tableData.length,
    pending: 0,
    resolved: 0,
    urgent: 0
  };
  
  state.tableData.forEach(row => {
    if (row.status === 'pending') stats.pending++;
    if (row.status === 'resolved') stats.resolved++;
    if (row.priority === 'urgent') stats.urgent++;
  });
  
  state.statistics = stats;
};

// 查看工单详情
const viewWorkOrder = async (row: WorkOrder) => {
  currentWorkOrder.value = row;
  
  // 解析对话历史
  if (row.conversationHistory) {
    try {
      conversationHistory.value = JSON.parse(row.conversationHistory);
    } catch {
      conversationHistory.value = [];
    }
  }
  
  workOrderDetailVisible.value = true;
};

// 处理工单
const processWorkOrder = async (row: WorkOrder) => {
  try {
    const { value } = await ElMessageBox.prompt('请输入处理意见：', '处理工单', {
      confirmButtonText: '确认处理',
      cancelButtonText: '取消',
      inputType: 'textarea',
      inputPlaceholder: '请输入处理意见...',
    });
    
    await customerServiceApi.updateWorkOrder({
      id: row.id,
      status: 'processing',
      assignedTo: 1, // 当前用户ID
      assignedToName: '当前用户',
      updateTime: new Date().toISOString(),
      description: `${row.description}\n\n处理意见：${value}`
    });
    
    ElMessage.success('工单处理成功');
    await handleQuery();
  } catch (error) {
    // 用户取消操作
  }
};

// 解决工单
const resolveWorkOrder = async (row: WorkOrder) => {
  try {
    const { value } = await ElMessageBox.prompt('请输入解决方案：', '解决工单', {
      confirmButtonText: '确认解决',
      cancelButtonText: '取消',
      inputType: 'textarea',
      inputPlaceholder: '请输入解决方案...',
    });
    
    await customerServiceApi.updateWorkOrder({
      id: row.id,
      status: 'resolved',
      updateTime: new Date().toISOString(),
      description: `${row.description}\n\n解决方案：${value}`
    });
    
    ElMessage.success('工单解决成功');
    await handleQuery();
  } catch (error) {
    // 用户取消操作
  }
};

// 批量处理
const batchProcess = async (rows: WorkOrder[]) => {
  if (!rows.length) return ElMessage.warning('请先选择工单');
  
  const pendingRows = rows.filter(row => row.status === 'pending');
  if (!pendingRows.length) {
    return ElMessage.warning('所选工单中没有待处理状态的工单');
  }
  
  await ElMessageBox.confirm(`确认处理选中的 ${pendingRows.length} 条工单吗？`, '批量处理');
  
  try {
    await Promise.all(pendingRows.map(row => 
      customerServiceApi.updateWorkOrder({
        id: row.id,
        status: 'processing',
        assignedTo: 1,
        assignedToName: '当前用户',
        updateTime: new Date().toISOString()
      })
    ));
    
    ElMessage.success(`成功处理 ${pendingRows.length} 条工单`);
    await handleQuery();
  } catch (error) {
    ElMessage.error('批量处理失败，请重试');
  }
};

// 获取状态类型
const getStatusType = (status: string) => {
  const typeMap = {
    'pending': 'warning',
    'processing': 'primary',
    'resolved': 'success',
    'closed': 'info'
  };
  return typeMap[status] || 'info';
};

// 获取状态文本
const getStatusText = (status: string) => {
  const textMap = {
    'pending': '待处理',
    'processing': '处理中',
    'resolved': '已解决',
    'closed': '已关闭'
  };
  return textMap[status] || '未知';
};

// 获取优先级类型
const getPriorityType = (priority: string) => {
  const typeMap = {
    'low': 'info',
    'medium': 'primary',
    'high': 'warning',
    'urgent': 'danger'
  };
  return typeMap[priority] || 'info';
};

// 获取优先级文本
const getPriorityText = (priority: string) => {
  const textMap = {
    'low': '低',
    'medium': '中',
    'high': '高',
    'urgent': '紧急'
  };
  return textMap[priority] || '未知';
};

// 获取分类文本
const getCategoryText = (category: string) => {
  const textMap = {
    'inventory': '库存问题',
    'order': '订单问题',
    'warehouse': '仓库操作',
    'system': '系统问题',
    'other': '其他'
  };
  return textMap[category] || '未知';
};

// 格式化时间
const formatTime = (timestamp: string) => {
  const date = new Date(timestamp);
  return date.toLocaleString('zh-CN');
};

onMounted(handleQuery);
</script>

<style scoped>
.work-order-container {
  padding: 10px;
}

.work-order-detail {
  max-height: 600px;
  overflow-y: auto;
}

.description-content {
  background: #f5f5f5;
  padding: 15px;
  border-radius: 4px;
  white-space: pre-wrap;
  line-height: 1.6;
}

.conversation-history {
  max-height: 300px;
  overflow-y: auto;
}

.conversation-item {
  margin-bottom: 15px;
  padding: 10px;
  border-radius: 8px;
}

.conversation-item.user {
  background: #e3f2fd;
  margin-left: 20px;
}

.conversation-item.agent {
  background: #f3e5f5;
  margin-right: 20px;
}

.conversation-header {
  display: flex;
  justify-content: space-between;
  margin-bottom: 5px;
  font-size: 12px;
  color: #666;
}

.sender {
  font-weight: bold;
}

.conversation-content {
  line-height: 1.5;
  white-space: pre-wrap;
}
</style>
